// pages/goods/detail.js
//自定义标题栏 详情页面

var http = require("../../utils/http.js");

import api from '../../utils/api';
import message from '../../utils/message';
import store from '../../utils/store';
import validate from '../../utils/validate'


Page({

  /**
   * 页面的初始数据
   */
  data: {

    detail:{},
    hasLoad:false,
    nums:1,
    static_url:'',
    indicatorDots: true,
    vertical: false,
    autoplay: false,
    interval: 2000,
    duration: 500,
    imageList:[],
    share_info:null,
    comment_list:[],
    sku_index:-1,
    select_sku:null,
    is_show_sku:false,
    content:[],
    content_tab_index:0,
    toview:'view_product',
    is_show_menu:false,
    attr_index:[ -1,-1 ],
    product_sku:null,
    retail_user:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var me = this;
    console.log(options);


    //message.show_error(JSON.stringify(options))

    const app = getApp();

    var id = options.id;

    var params = {};
    params.id = id;

    if(options.retail_id){
      params.retail_id = options.retail_id
    }
    http.doGet("/Product/detail" , params  , function( resp){
      var result = resp.data;

      if(result.status==1){
        //检验产品是否出售中， 是否允许购买，是否有错误。
        /*

        var imageList = []

        if( validate.isJson( result.data.detail.product_images )){
          imageList = JSON.parse(result.data.detail.product_images);

        }

        */

        //渲染评论图片数据为数组元素
        
        var comment_list = result.data.comment_list;
        for(var i=0;i<comment_list.length ; i++){
          comment_list[i].images = JSON.parse( comment_list[i].images );
        }

        //商品详情
        var content = [];
        if(result.data.detail.content!=null){

          try{
            content = JSON.parse( result.data.detail.content);
          }catch( error){
            content = []
          }
          
        }

        var product_sku = null;

        if(result.data.detail.is_sku==1){

          if(result.data.detail.product_skus.length>0){
            product_sku = result.data.detail.product_skus[0];
          }
        }
       
        //var imageList = JSON.parse(result.data.product_images);

        var share_info = null;
        if(result.data.share_info ){
            share_info = result.data.share_info
        }
        me.setData({
          detail: result.data.detail,
          share_info: share_info,
          imageList: result.data.detail.product_images,
          hasLoad: true,
          comment_list: comment_list,
          content:content,
          product_sku:product_sku,
          retail_user:result.data.retail_user
        })


        if(result.data.detail.status!=1){
          
          message.show_error("当前商品已下架，快去选购别的商品吧" , function(){
            wx.navigateBack({
              delta: 1,
            })
          });
          return;
        }
      }



    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {

    if(res.from=='button'){
      console.log("点击按钮");
    }

    var me = this;

    var image_url = me.data.static_url+me.data.detail.product_thumb;



    if(me.data.share_info!=null){
      return me.data.share_info;
    }

    return {
      title: me.data.detail.name,
      path: 'pages/goods/detail?id='+me.data.detail.id,
      imageUrl: image_url,
      success:function(res){
        // 转发成功之后的回调
　　　　　if(res.errMsg == 'shareAppMessage:ok'){
　　　　　}
      },
      fail: function(){
        // 转发失败之后的回调
        if(res.errMsg == 'shareAppMessage:fail cancel'){
        　// 用户取消转发
          console.log("取消转发");
        }else if(res.errMsg == 'shareAppMessage:fail'){
        　　// 转发失败，其中 detail message 为详细失败信息
          console.log("转发失败");
        }
      },
    }
  },
  getProductDetail:function () {
    //加载产品详情
    
    api.product.getProductDetail();
  },

  selectContentTab:function(e ){
    var index = e.currentTarget.dataset.index;
    this.setData({
      content_tab_index:index
    })
  },
  selectProductSku:function( e ){
    var data_index = e.currentTarget.dataset.index;
    var sku_item = this.data.detail.product_skus[data_index];
    console.log(sku_item);
    this.setData({
      sku_index:data_index,
      select_sku:sku_item
    })
  },

  selectProductSku2:function(e){
    var action=e.currentTarget.dataset.action;
    if(action==1){
      this.setData({
        is_show_sku:true
      })

    }

    if(action==-1){
      this.setData({
        is_show_sku:false
      })
    }
  },

  closeBox:function(e){
    var action = e.currentTarget.dataset.action;
    if(action=="sku"){
      this.setData({
        is_show_sku:false
      })
    }

  },

  

  goCart:function(){
    wx.switchTab({
      url: '/pages/cart/cart',
    })
  },
  addToCart:function(){
    //添加购物车

    var nums = this.data.nums;
    var id = this.data.detail.id;

    var params = {
      "product_id":id,
      "product_nums":nums
    }
    api.cart.addProduct( params , function(response){
      if(response.status==99){

        message.alert("提示" , response.message , "取消" , "确定" , function(){

          console.log("点击确定")
          wx.navigateTo({
            url: '/pages/login/login',
          })

        });

        return ;
      }

      if(response.status==1){
        wx.showToast({
          title: '成功添加到购物车',
        })
      }else{

        console.log(response.message)
        
      }
    })


    /*
    var detail = this.data.detail;
    var obj = Object.assign( detail , { nums:nums } )
    var status = store.addProduct(obj);
    //console.log(obj);

    if(status){
      wx.showToast({
        title: '成功添加到购物车',
      })

      wx.setTabBarBadge({
        index: 2,
        text: 5,
      })
    }

    */
  },

  addSkuToCart:function () {
    //添加sku 商品

    if( !this.data.product_sku ){
      message.show_error("请选择商品");
      return ;
    }

    var params = {};

    params.product_id = this.data.detail.id;
    params.product_sku_id = this.data.product_sku.id;


    params.product_nums = this.data.nums;

    api.cart.addSkuToCart( params , function (res) {
      console.log(res)

      if(res.status==1){
        message.toast(res.message)

      }else{
        message.show_error(res.message)
      }
        
    });
    
  },
  addNums:function(){
    var nums = this.data.nums;
    nums++;
    this.setData({
      nums:nums
    })
  },
  reduceNums:function(){
    var nums = this.data.nums;
    nums--;
    if(nums<1){
      nums = 1;

        wx.showToast({
          title: "最少购买1件",
          icon:'none'
        })
      
    }
    this.setData({
      nums:nums
    })
  },

  saveProduct:function(){
  },
  goBack:function(){
    wx.navigateBack({
      delta: 1,
    })
  },
  gojump:function( e ){
    var view_id = e.currentTarget.dataset.id

    this.setData({
        toview: view_id
    })
  },
  pageScroll:function(e){
    var that = this;
    let currentY = e.detail.scrollTop;
    var data = this.data.is_show_menu;

    if(currentY>=300){
        this.setData({
            is_show_menu:true
        })
    }else{
        this.setData({
            is_show_menu:false
        })
    }
  },
  selectAttrValue:function (e) {
    var me  = this;
    var index = e.currentTarget.dataset.index;
    var child = e.currentTarget.dataset.child;

    var attr_index = this.data.attr_index;
    attr_index[index] = child;
    
    this.setData({
      attr_index:attr_index
    })

    for(var i in attr_index){
      if(attr_index[i]<=0){
        return;
      }
    }

    var sku_id = attr_index.join("_");
    api.product.getProductSku({sku_id:sku_id} , function (response) {
      console.log(response)

      if(response.status==1){
        me.setData({
          product_sku:response.data
        })

      }else{
        me.setData({
          product_sku:null
        })

      }
    })

    //如果属性都选择齐全，则查找商品信息

  },
  selectProducSku:function (e) {
    var index = e.currentTarget.dataset.index;

    var product_sku = this.data.detail.product_skus[index];

    if(!product_sku){
      message.show_error("当前商品不存在");
    }else{
      this.setData({
        product_sku:product_sku
      })
    }
    
  }
})